class Compiler {
  constructor(vm) {
    this.el = vm.$el;
    this.vm = vm;
    this.compiler(this.el);
  }

  // 编译模板，处理文本和元素节点
  compiler(el) {
    let childNodes = el.childNodes;
    Array.from(childNodes)
      .forEach(node => {
        // 处理文本节点
        if (this.isTextNode(node)) {
          this.compilerText(node);
        }
        // 处理元素节点
        else if (this.isElementNode(node)) {
          this.compilerElement(node);
        }
        // 判断是否有子节点 递归调用处理节点
        if (node.childNodes && node.childNodes.length) {
          this.compiler(node);
        }
      });
  }

  // 编译元素节点，处理指令
  compilerElement(node) {
    Array.from(node.attributes)
      .forEach(attr => {
        let attrName = attr.name;
        if (this.isDirective(attrName)) {
          attrName = attrName.substr(2);
          let key = attr.value;
          this.update(node, key, attrName);
        }
      });
  }

  update(node, key, attrName) {
    // 拼接方法名称 减少if判断 并且便于更新
    let updateFn = this[attrName + 'Updater'];
    updateFn && updateFn.call(this, node, this.vm[key], key);
  }

  textUpdater(node, value, key) {
    node.textContent = value;
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue;
    });
  }

  modelUpdater(node, value, key) {
    node.value = value;
    new Watcher(this.vm, key, (newValue) => {
      node.value = newValue;
    });
  }

  onUpdater(node, value, key) {
    node['on' + key] = this.vm.$options.method[key];
  }

  htmlUpdater(node, value, key) {
    node.textContent = value;
    new Watcher(this.vm, key, (newValue) => {
      node.textContent = newValue;
    });
  }

  // 编译文本节点，处理插值表达式
  compilerText(node) {
    let reg = /{{(.+?)}}/;
    let value = node.textContent;
    if (reg.test(value)) {
      let key = RegExp.$1.trim();
      node.textContent = value.replace(reg, this.vm[key]);

      // watcher对象 当数据改变更新视图
      new Watcher(this.vm, key, (newValue) => {
        node.textContent = newValue;
      });
    }

  }

  isDirective(attrName) {
    return attrName.startsWith('v-');
  }

  isTextNode(node) {
    // nodeType =3 为文本节点
    return node.nodeType === 3;
  }

  isElementNode(node) {
    // nodeType =1 为元素节点
    return node.nodeType === 1;
  }
}
